package com.deyuanyun.pic.pig.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.deyuanyun.pic.common.cache.TempStoreDataSupport;
import com.deyuanyun.pic.common.dto.PageJsonBean;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.UploadUtil;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.domain.base.Attachment;
import com.deyuanyun.pic.pig.domain.CleanPipeLineManagerVo;
import com.deyuanyun.pic.pig.domain.InspSegment;
import com.deyuanyun.pic.pig.domain.PigTask;
import com.deyuanyun.pic.pig.service.CleanPipeLineManagerService;
import com.deyuanyun.pic.pipe.service.ValveRoomService;
import com.deyuanyun.pic.service.pipe.PipeLineService;

/**
 * 清管管理控制类
 * 
 * @author tt
 *
 */
@Controller
@RequestMapping("/cleanTask/cleanPipeLineManager")
public class CleanPipeLineManagerController extends PiggingBaseController {

	private static final String path = UploadUtil.ROOTPATH + UploadUtil.OTHERRES;

	@Resource
	private CleanPipeLineManagerService cleanPipeLineManagerService;

	@Resource(name = "pipeLineServiceImpl")
	private PipeLineService pipeLineService;
	
	@Resource
	private ValveRoomService pipeValveRoomService;
	/**
	 * 跳转到任务管理页面
	 * 
	 * @return
	 */
	@RequestMapping("goPiggingManagerPage.html")
	public ModelAndView goPiggingManagerPage() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pipeLine", pipeLineService.getLine());
		return forword("/pig/cleanPipeLineManager", map);
	}

	/**
	 * 加载任务列表数据
	 */
	@RequestMapping("getCleanPipeLineManagerIndex.json")
	@ResponseBody
	public void getCleanPipeLineManagerIndex(CleanPipeLineManagerVo taskVo) {
		PageJsonBean jsonBean = new PageJsonBean();
		List list = cleanPipeLineManagerService.getCleanPipeLineManagerIndex(taskVo);
		jsonBean.setList(list);
		AjaxSupport.sendSuccessText("", jsonBean);
	}

	/**
	 * 任务删除
	 * 
	 * @param idsArr
	 * @return
	 */
	@RequestMapping("/deleteFun.json")
	@ResponseBody
	public void deleteFun(String idStr) throws Exception {
		Asserts.assertTrue(!StringUtils.isEmpty(idStr), "数据异常，请刷新页面后重试");
		// int i = 0;
		// Map<String,Object> map = new HashMap<String,Object>();
		// map = cleanPipeLineManagerService.deleteFunById(idStr);
		AjaxSupport.sendSuccessText("", cleanPipeLineManagerService.deleteFunById(idStr));
	}

	/**
	 * 任务发布
	 * 
	 * @param idsArr
	 * @return
	 */
	@RequestMapping("/publishFun.json")
	@ResponseBody
	public void publishFun(String idStr) throws Exception {
		Asserts.assertTrue(!StringUtils.isEmpty(idStr), "数据异常，请刷新页面后重试");
		int i = 0;
		i = cleanPipeLineManagerService.publishFunById(idStr);
		AjaxSupport.sendSuccessText("", i);
	}

	/**
	 * 获取管段
	 * 
	 * @param lineId
	 * @return
	 */
	@RequestMapping("/getInspSegment.json")
	@ResponseBody
	public void getInspSegment(String lineId) {
		List<InspSegment> ls = new ArrayList<>();
		if (!"".equals(lineId) && null != lineId) {
			ls = cleanPipeLineManagerService.getSegment(lineId);
		}
		AjaxSupport.sendSuccessText("", ls);
	}

	/**
	 * 根据管段ID获取对应的mark点
	 * 
	 * @param inspSegmentId
	 * @return
	 */
	@RequestMapping("/getMarkPoint.json")
	@ResponseBody
	public void getMarkPoint(String inspSegmentId) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (!"".equals(inspSegmentId) && null != inspSegmentId) {
			map = cleanPipeLineManagerService.getMarkPoint(map, inspSegmentId);
		}
		AjaxSupport.sendSuccessText("", map);
	}

	/**
	 * 保存检测任务
	 * 
	 * @param taskVo
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping("/saveTask.json")
	@ResponseBody
	public void saveTask(HttpServletRequest request, CleanPipeLineManagerVo taskVo, String reverse,
			@RequestParam("file") MultipartFile[] file) throws Exception {
		Asserts.assertTrue(!StringUtils.isEmpty(taskVo.getTaskName().trim()), "请填写任务名称");
		Asserts.assertTrue(!StringUtils.isEmpty(taskVo.getLineId()), "请选择管道");
		Asserts.assertTrue(!StringUtils.isEmpty(taskVo.getSegmentId()), "请选择管段");
		Asserts.assertTrue(!StringUtils.isEmpty(taskVo.getMarkPoint()), "请勾选跟踪点");
		Asserts.assertTrue(!StringUtils.isEmpty(taskVo.getFromPigStr()), "没有发球桶，请重新选择管段");
		Asserts.assertTrue(!StringUtils.isEmpty(taskVo.getToPigIdStr()), "没有收球桶，请重新选择管段");
		Asserts.assertTrue(!StringUtils.isEmpty(taskVo.getType()), "请选择清管类型");
		Asserts.assertTrue(!StringUtils.isEmpty(taskVo.getPigType()), "请选择或填写清管工具");
		Asserts.assertTrue(!StringUtils.isEmpty(taskVo.getPlanPagDateTime()), "请填写计划清管时间");
		Asserts.assertTrue(!StringUtils.isEmpty(reverse), "没有获取到收发球筒是否易位的数据");
		
		String taskId = taskVo.getTaskId();
		String taskName = taskVo.getTaskName();
		String lineId = taskVo.getLineId();
		String segmentId = taskVo.getSegmentId();
		String markPoint = taskVo.getMarkPoint();
		String fromPig = taskVo.getFromPigStr();
		String toPig = taskVo.getToPigIdStr();
		String remark = taskVo.getRemark();
		String type = taskVo.getType();
		String pigType = taskVo.getPigType();
		String planPagDateTime = taskVo.getPlanPagDateTime()+":00";
		
		Map<String, Object> map = new HashMap<String, Object>();
		map = cleanPipeLineManagerService.saveTask(map, taskId, taskName, lineId, segmentId, markPoint, fromPig, toPig,
				remark, type, pigType, planPagDateTime,reverse);
		String tid = "";
		if (ObjectUtil.isNotNullEmpty(map.get("tid"))) {
			tid = map.get("tid").toString();
		}
		if (!StringUtils.isEmpty(tid)) {
			for (int i = 0; i < file.length; i++) {
				if (!file[i].isEmpty()) {
					// 取得当前上传文件的文件名称
					String sourceName = file[i].getOriginalFilename();
					String fileType = sourceName.substring(sourceName.lastIndexOf("."), sourceName.length());
					// 重命名文件
					String targetName = UUID.randomUUID().toString().replace("-", "") + fileType;
					// 定义上传路径
					File localFile = new File(path, targetName);
					if (!localFile.exists()) {
						localFile.mkdirs();
					}
					file[i].transferTo(localFile);
					cleanPipeLineManagerService.savefile(sourceName, UploadUtil.OTHERRES + targetName, tid);
				}
			}
		}
		AjaxSupport.sendSuccessText("", map);
	}

	/**
	 * 修改时获取任务
	 * 
	 * @param taskId
	 * @return
	 */
	@RequestMapping("/getTask")
	@ResponseBody
	public void getTask(String taskId) {
		Asserts.assertTrue(!StringUtils.isEmpty(taskId), "获取任务数据异常，请刷新页面重试");
		PigTask task = cleanPipeLineManagerService.getTask(taskId);
		AjaxSupport.sendSuccessText("", task);
	}

	/**
	 * 新增或修改任务
	 * 
	 * @param taskId
	 * @return
	 */
	@RequestMapping("/addOrModify.html")
	public ModelAndView addOrModify(String taskId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map = cleanPipeLineManagerService.addOrModify(taskId, map);
		return forword("/pig/addOrModify", map);
	}
	
	/**
	 * 获取清管工具
	 * 
	 * @param name
	 * @return
	 */
	@RequestMapping("/getCleanTool.json")
	@ResponseBody
	public void getCleanTool(String name) {
		Map<String, Object> map = new HashMap<String, Object>();

		if (null != name && !"".equals(name)) {
			map = cleanPipeLineManagerService.getCleanTool(name);
		}
		AjaxSupport.sendSuccessText("", map);
	}

	/**
	 * 获取复制任务弹窗数据
	 * 
	 * @param taskId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/copyTask.json")
	@ResponseBody
	public void copyTask(String taskId) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(taskId)) {
			map = cleanPipeLineManagerService.copyTask(taskId);
		}
		AjaxSupport.sendSuccessText("", map);
	}

	/**
	 * 保存复制的任务
	 * 
	 * @param taskId
	 * @param cleanTool
	 * @param remark
	 * @param taskName
	 * @param planTime
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/copySave.json")
	@ResponseBody
	public void copySave(String taskId, String cleanTool, String remark, String taskName, String planTime,String fromPig,String toPig)
			throws Exception {
		Asserts.assertTrue(!StringUtils.isEmpty(taskId), "数据异常，请刷新页面后重试");
		Asserts.assertTrue(!StringUtils.isEmpty(taskName.trim()), "任务名称不能为空");
		Asserts.assertTrue(!StringUtils.isEmpty(cleanTool), "清管工具不能为空");
		Asserts.assertTrue(!StringUtils.isEmpty(planTime), "计划时间不能为空");
		Asserts.assertTrue(!StringUtils.isEmpty(fromPig), "发球筒不能为空");
		Asserts.assertTrue(!StringUtils.isEmpty(toPig), "收球筒不能为空");
		Map<String, Object> map = new HashMap<String, Object>();
		map = cleanPipeLineManagerService.copySave(taskId, cleanTool, remark, taskName, planTime,fromPig,toPig);
		AjaxSupport.sendSuccessText("", map);
	}

	/**
	 * 下载任务附件
	 * 
	 * @param taskId
	 */
	@RequestMapping("/downloadTaskFile.json")
	@ResponseBody
	public void downloadTaskFile(HttpServletResponse response, String taskId) throws Exception {
		Asserts.assertTrue(!StringUtils.isEmpty(taskId), "数据异常，请稍后重试");
		// 相关附件
		List<Attachment> attaList = cleanPipeLineManagerService.downloadTaskFile(taskId);
		// 任务名称
		PigTask task = cleanPipeLineManagerService.getTask(taskId);
		// 磁盘文件名
		String diskName = "";
		// 下载的文件名
		String downName = "";
		byte[] buffer = new byte[1024];
		if (attaList.size() > 1) { // 如果不止一条附件。则打包下载
			if (ObjectUtil.isNotNullEmpty(task)) {
				downName = task.getName();
			}
			// 所有附件
			List<File> files = new ArrayList<File>();
			downName = downName + "的所有附件.rar";
			diskName = path + downName;
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(diskName));
			for (Attachment att : attaList) {
				if (ObjectUtil.isNotNullEmpty(att)) {
					if (ObjectUtil.isNotNullEmpty(att.getId())) {
						files.add(new File(UploadUtil.ROOTPATH + att.getPath()));
					}
				}
			}
			for (int i = 0; i < files.size(); i++) {
				FileInputStream fis = new FileInputStream(files.get(i));
				out.putNextEntry(new ZipEntry(files.get(i).getName()));
				// 设置压缩文件内的字符编码，不然会变成乱码
				// out.setEncoding("GBK");
				int len;
				// 读入需要下载的文件的内容，打包到zip文件
				while ((len = fis.read(buffer)) > 0) {
					out.write(buffer, 0, len);
				}
				out.closeEntry();
				fis.close();
			}
			out.close();
			downFile(response, diskName, downName);
		} else if (attaList.size() == 1) {
			diskName = attaList.get(0).getPath();
			downName = attaList.get(0).getRealName();
			downFile(response, diskName, downName);
		} else {
			response.setHeader("Content-Disposition", "");
			AjaxResponse.sendText(response, "<script>alert('该任务没有附件,无需下载');</script>");
		}
	}

	/**
	 * 文件下载
	 * 
	 * @param response
	 * @param str
	 * @throws Exception
	 */
	@ResponseBody
	private void downFile(HttpServletResponse response, String diskName, String downName) throws Exception {
		String filePath = UploadUtil.ROOTPATH + diskName;
		File file = new File(filePath);
		if (file.exists()) {
			InputStream ins = new FileInputStream(filePath);
			BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面
			OutputStream outs = response.getOutputStream();// 获取文件输出IO流
			BufferedOutputStream bouts = new BufferedOutputStream(outs);
			response.setContentType("application/x-download; charset=utf-8");// 设置response内容的类型
			response.setCharacterEncoding("UTF-8");
			// response.setHeader("Content-disposition", "attachment;filename="
			// + URLEncoder.encode(downName, "UTF-8"));// 设置头部信息
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(downName.getBytes("gb2312"), "ISO8859-1"));

			int bytesRead = 0;
			byte[] buffer = new byte[2048];
			// 开始向网络传输文件流
			while ((bytesRead = bins.read(buffer, 0, 2048)) != -1) {
				bouts.write(buffer, 0, bytesRead);
			}
			bouts.flush();
			ins.close();
			bins.close();
			outs.close();
			bouts.close();
		}
	}
	
	/**
	 * 收发球易位
	 * @param taskId
	 * @param segmentId
	 * @param adverseCurrent 是否易位【0：否 1：是】
	 */
	@RequestMapping("/transPig.json")
	@ResponseBody
	public void transPig(String taskId,String segmentId,String adverseCurrent){
		Asserts.assertTrue(!StringUtils.isEmpty(segmentId), "没有找到对应的管段");
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("taskId", taskId);
		map.put("segmentId", segmentId);
		map.put("adverseCurrent", adverseCurrent);
//		List list = cleanPipeLineManagerService.transPig(map);
	}
	
	/**
	 * 查询所有的场站阀室
	 */
	@RequestMapping("/findAllValueRoom.json")
	@ResponseBody
	public void findAllValueRoom(String segmentId,String reverse){
		List<HashMap<String, Object>> data=pipeValveRoomService.findValveRoomCenterPoint();
		StringBuffer json=new StringBuffer("[");
		for(HashMap<String,Object> v : data){
			json.append("{");
			json.append("\"lng\":").append(v.get("CONVERT_X")).append(",").append("\"lat\":").append(v.get("CONVERT_Y")).append(",");
			json.append("\"name\":\"").append(v.get("SHOW_NAME")).append("\",").append("\"state\":").append(v.get("ISCGSZ"));
			json.append("},");
		}
		if(data.size() >0)
		{
			json.deleteCharAt(json.length()-1);
		}
		json.append("]");
		//检测管段上的点
		Map<String,Object> map2 = new HashMap<String,Object>();
		map2.put("segmentId", segmentId);
		map2.put("reverse", reverse);
		//检测管段上的点
		List<HashMap<String, Object>> data2 = cleanPipeLineManagerService.findZuoBiaoByInspSegmentId(map2);
		//改检测管段上的所有物理管段
		List<String> allPipeSegment = cleanPipeLineManagerService.findAllSegmentByInspSegmentId(segmentId);
		StringBuffer json2=new StringBuffer("[");
		for (String sId : allPipeSegment) {
			if(ObjectUtil.isNotNullEmpty(sId)){
				json2.append("{").append("\"location\":").append("[");
				for (HashMap<String, Object> v2 : data2) {
					if(sId.equals(v2.get("PIPE_SEGMENT_ID").toString())){
						json2.append("\"").append(v2.get("LNG")).append(";").append(v2.get("LAT")).append("\"").append(",");
					}
				}
				json2.deleteCharAt(json2.length()-1);
				json2.append("]},");
			}
		}
		if(data2.size() >0)
		{
			json2.deleteCharAt(json2.length()-1);
		}
		json2.append("]");
		Map<String,String> m=new HashMap<String,String>();
		m.put("data", json.toString());
		m.put("data2", json2.toString());
		m.put("type", "1");
		AjaxSupport.sendSuccessText("ok", m);
	}
	
	/**
	 * 提供给GIS端访问de接口
	 * 查询所有的基础数据 用于地图显示
	 * @param map
	 */
	@RequestMapping("/findAllMapData.json")
	@ResponseBody
	public void findAllMapData(@RequestParam  Map<String,Object> map){
		double lngMin = 0;
		double lngMax = 0;
		double latMin = 0;
		double latMax = 0;
		String pre = "map_Data_tkc";
		String type = (String)(map.get("type"));
		Map<String,Object> pramMap = new HashMap<String,Object>();
		if (ObjectUtil.isNotNullEmpty(map.get("lngMin")) && ObjectUtil.isNotNullEmpty(map.get("lngMax"))
				&& ObjectUtil.isNotNullEmpty(map.get("latMin")) && ObjectUtil.isNotNullEmpty(map.get("latMax"))) {
			lngMin = Double.valueOf(map.get("lngMin").toString());
			lngMax = Double.valueOf(map.get("lngMax").toString());
			latMin = Double.valueOf(map.get("latMin").toString());
			latMax = Double.valueOf(map.get("latMax").toString());
		}
		pramMap.put("lngMin", lngMin);
		pramMap.put("lngMax", lngMax);
		pramMap.put("latMin", latMin);
		pramMap.put("latMax", latMax);
		pramMap.put("type", type);
		List<Map<String,Object>> list = null;
		StringBuffer json=new StringBuffer("[");
		
		/*if("pipecross".equals(type)){
			for (String crossId : crossList) {
				if(!StringUtils.isEmpty(crossId)){
					json.append("{");
					json.append("\"location\":").append("[");
					pramMap.put("id", crossId);
					list = TempStoreDataSupport.pullData(pre + crossId);
					if(ObjectUtil.isEmptyAll(list)){
						list = cleanPipeLineManagerService.findAllMapData(pramMap);
						TempStoreDataSupport.pushDataByTimeMinute(pre + crossId, list,6000);
					}
					for (int i = 0; i < list.size(); i++) {
						json.append("\"").append(list.get(i).get("LNG")).append(";").append(list.get(i).get("LAT")).append("\"").append(",");
					}
					if(',' == json.charAt(json.length() - 1)){
						json = json.delete(json.lastIndexOf(","), json.length());
					}
					json.append("]").append("},");
				}
			}
		}else{*/
			String key[] = {"tee","identification","piggingstructure","valve","celbow","elbow","pipecross","pipeinfo"};
			String prama = String.valueOf(lngMin + lngMax + latMin + latMax);
			if (type.equals(key[0])) {
				list = TempStoreDataSupport.pullData(pre + key[0] + prama);
				if (ObjectUtil.isEmptyAll(list)) {
					list = cleanPipeLineManagerService.findAllMapData(pramMap);
					TempStoreDataSupport.pushDataByTimeMinute(pre + key[0], list, 6000);
				}
			}
			if (type.equals(key[1])) {
				list = TempStoreDataSupport.pullData(pre + key[1] +prama);
				if (ObjectUtil.isEmptyAll(list)) {
					list = cleanPipeLineManagerService.findAllMapData(pramMap);
					TempStoreDataSupport.pushDataByTimeMinute(pre + key[1], list, 600);
				}
			}
			if (type.equals(key[2])) {
				list = TempStoreDataSupport.pullData(pre + key[2] + prama);
				if (ObjectUtil.isEmptyAll(list)) {
					list = cleanPipeLineManagerService.findAllMapData(pramMap);
					TempStoreDataSupport.pushDataByTimeMinute(pre + key[2], list, 600);
				}
			}
			if (type.equals(key[3])) {
				list = TempStoreDataSupport.pullData(pre + key[3] + prama);
				if (ObjectUtil.isEmptyAll(list)) {
					list = cleanPipeLineManagerService.findAllMapData(pramMap);
					TempStoreDataSupport.pushDataByTimeMinute(pre + key[3], list, 600);
				}
			}
			if (type.equals(key[4])) {
				list = TempStoreDataSupport.pullData(pre + key[4] + prama);
				if (ObjectUtil.isEmptyAll(list)) {
					list = cleanPipeLineManagerService.findAllMapData(pramMap);
					TempStoreDataSupport.pushDataByTimeMinute(pre + key[4], list, 600);
				}
			}
			if (type.equals(key[5])) {
				list = TempStoreDataSupport.pullData(pre + key[5] +prama);
				if (ObjectUtil.isEmptyAll(list)) {
					list = cleanPipeLineManagerService.findAllMapData(pramMap);
					TempStoreDataSupport.pushDataByTimeMinute(pre + key[5], list, 600);
				}
			}
			if(type.equals(key[6])){
				list = TempStoreDataSupport.pullData(pre + key[6] + prama);
				if (ObjectUtil.isEmptyAll(list)) {
					list = cleanPipeLineManagerService.findAllMapData(pramMap);
					TempStoreDataSupport.pushDataByTimeMinute(pre + key[6], list, 600);
				}
			}
			if(list.size() > 0){
				for (Map<String, Object> v : list) {
					json.append("{");
					json.append("\"lng\":").append(v.get("LNG")).append(",").append("\"lat\":").append(v.get("LAT")).append("},");
				}
			}
//		}
		if(list.size() >0) {
			json.deleteCharAt(json.length()-1);
		}
		json.append("]");
		Map<String,String> m=new HashMap<String,String>();
		m.put("data", json.toString());
		AjaxSupport.sendSuccessText("ok", m);
	}
}
